package com.zeratul.common.core.utils;

import cn.hutool.core.util.ObjectUtil;

import java.util.Base64;

/**
 * 位操作工具类
 */
public class BitUtils {

    /**
     * 创建一个位图
     * @param bitSize
     * @return
     */
    public static byte[] createBitMap(Long bitSize) {
        if (ObjectUtil.isNull(bitSize))  {
            return null;
        }
        return new byte[(bitSize.intValue() + 7) / 8];
    }


    /**
     * 将位图下标start 到 end的位置全部设置为1
     * 0000 0001
     * @param bitMap
     * @param start
     * @param over
     * @return
     */
    public static int setBitMap(byte[] bitMap, Long start, Long over){
        //有效秒数的长度
        int bitCount = 0;

        //位图是从0开始的，所以下标要减去1
        start = start - 1;
        over = over - 1;

        //避免越界问题
        if (start < 0) {
            start = 0L;
        }
        if (over < 0) {
            over = 0L;
        }

        int begin = (int) Math.min(start, bitMap.length * 8 - 1);
        int end = (int) Math.min(over, bitMap.length * 8 - 1);

        for(int i = begin; i <= end; i++){
            if ((bitMap[i / 8] & (1 << (7 - (i % 8)))) != 0) {
                continue;
            }
            bitMap[i / 8] |= (1 << (7 - (i % 8)));
            bitCount++;
        }
        return bitCount;
    }

    /**
     * 统计位图中1的个数
     */
    public static int countBitMap(byte[] bitMap) {

        if (ObjectUtil.isNull(bitMap)) {
            return 0;
        }

        int count = 0;
        for (int i = 0; i < bitMap.length; i++) {
            for (int j = 0; j < 8; j++) {
                if ((bitMap[i] & (1 << j)) != 0) {
                    count++;
                }
            }
        }
        return count;
    }


    /**
     * 将一个位图数组通过字符串打印出来，并且打印出每一位的下标
     */
    public static void printBitMap(byte[] bitMap) {
        if (ObjectUtil.isNull(bitMap)) {
            return;
        }
        for (int i = 0; i < bitMap.length; i++) {
            for (int j = 0; j < 8; j++) {
                if ((bitMap[i] & (1 << j)) != 0) {
                    System.out.print("1");
                } else {
                    System.out.print("0");
                }
            }
            System.out.print(" ");
            System.out.print(i * 8);
            System.out.println();
       }
    }

    /**
     * 将位图通过Base64转换成字符串
     */
    public static String bitMap2Base64(byte[] bitMap) {
        if (ObjectUtil.isEmpty(bitMap)) {
            return null;
        }
        return Base64.getEncoder().encodeToString(bitMap);
    }

    /**
     * 将字符串通过Base64转换成位图
     */
    public static byte[] base642BitMap(String base64) {
        if (ObjectUtil.isEmpty(base64)) {
            return null;
        }
        return Base64.getDecoder().decode(base64);
    }
}
